package com.redstar.interesting.common.starter.filter;

import com.redstar.interesting.common.constants.Constants;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.UUID;


/**
 * 服务提供方，如果没有traceId，则自己生成一个，并设置MDC中
 * @author lihongxing
 */
@Activate(group = {CommonConstants.PROVIDER})
public class DubboProviderTraceIdFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(DubboProviderTraceIdFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        setTraceId(invocation);
        long start = System.currentTimeMillis();
        try {
            logger.info("Dubbo provider url = {},methodName = {}",invocation.getInvoker().getUrl(),invocation.getMethodName());
            return invoker.invoke(invocation);
        }finally {
            logger.info("Dubbo request end. url = {},methodName = {}, 耗时 = {}ms",
                    invocation.getInvoker().getUrl(), invocation.getMethodName(), System.currentTimeMillis() - start);
            MDC.clear();
        }
    }


    private void setTraceId(Invocation invocation) {
        String traceId = invocation.getAttachment(Constants.TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put(Constants.TRACE_ID, traceId);
    }


}
